/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 */
package seedpod.model.custom;

import java.sql.ResultSet;
import java.sql.SQLException;

import seedpod.exceptions.SeedpodException;
import seedpod.kb2db.ClsMap;
import seedpod.kb2db.SlotMap;
import seedpod.model.NoObjectFoundException;
import seedpod.model.SeedpodDO;
import seedpod.model.SeedpodModel;
import seedpod.rdb.PManager;
import seedpod.webapp.controller.FailToAuthenticateException;
import seedpod.webapp.service.PasswordService;
import seedpod.webapp.service.SystemUnavailableException;

public class SeedpodUser extends SeedpodDO {
	private String _userName;

	private String _firstName;

	private String _lastName;

	private String _userGroup;

	private String _password;

	private boolean _isLoggedIn = false;

	private boolean _userExists = false; // TODO useful for err msg

	public SeedpodUser(int userID, PManager manager) throws NoObjectFoundException {
		super( SeedpodModel.RdbCls.USER, userID, manager );
		super._oid = userID;
	}

	/**
	 * create an user object with the user name
	 * 
	 * @param userName
	 * @param doFetch
	 *            if true, will fetch the object from the database
	 * @throws NoObjectFoundException
	 */
	public SeedpodUser(String userName, boolean dofetch, PManager manager) throws NoObjectFoundException {
		super( SeedpodModel.RdbCls.USER, manager );
		_userName = userName;

		try {
			if ( dofetch ) {
				ClsMap userClsMap = getMetaCls();
				SlotMap userAtt = userClsMap.getSlotMap( SeedpodModel.RdbSlot.USERNAME );
				setAttributeValue( userAtt, _userName );
				getSqlSelectLike( this );
				_userExists = true;
			}
		} catch (SeedpodException se) {
			_userExists = false;
		}
	}

	public SeedpodUser(String userName, Integer oid, PManager manager) throws NoObjectFoundException {
		super( userName, oid, manager );
	}

	public SeedpodUser(String userName, PManager manager) throws NoObjectFoundException {
		this( userName, false, manager );
	}

	public boolean authenticate( String pwd ) throws FailToAuthenticateException, SeedpodException, SystemUnavailableException {
		String enc = "";

		if ( _isLoggedIn ) {
			_userExists = true;
			return true;
		} else if ( _userName == null )
			throw new FailToAuthenticateException( " Please enter your SeedpodID. " );
		else if ( pwd == null )
			throw new FailToAuthenticateException( "Please enter your password." );
		else {
			enc = PasswordService.getInstance().encrypt( pwd );

			System.err.println( "enc: " + enc );
			System.err.println( "pwd: " + _password );

			if ( _password.equals( enc ) )
				return true;
			else throw new FailToAuthenticateException( explainFailure() );
		}
	}

	public boolean canEditData() {
		return true; // _userGroup == SeedpodModel.RdbCls.PERMISSION_ADMINISTRATOR;
	}

	public boolean exists() {
		// if the state is transient, check with the database
		if ( isDirty() ) try {
			boolean suc = getSqlSelectLike( this );
			if ( suc ) {
				makePersist();
				_userExists = true;
			} else _userExists = false;
		} catch (SeedpodException e) {
			makeTransient();
			_userExists = false;
		}

		return _userExists;
	}

	private String explainFailure() {
		String msg = "";
		if ( exists() )
			msg = _userName + ", you have inserted a bad password.";
		else msg = "Check your user name and password.";
		return msg;
	}

	public String getFirstName() {
		return _firstName;
	}

	@Override
	public String getLabel() {
		String label = getFirstName() + " " + getLastName();
		if ( label.trim().length() == 0 ) label = getUserName();
		return label;
	}

	public String getLastName() {
		return _lastName;
	}

	public String getPassword() {
		return _password;
	}

	public String getUserGroup() {
		return _userGroup;
	}

	public int getUserId() {
		return _oid;
	}

	public String getUserName() {
		return _userName;
	}

	public boolean isLoggedIn() {
		return _isLoggedIn;
	}

	@Override
	public void load( ResultSet rs ) throws SeedpodException, SQLException {
		if ( rs == null ) {
			makeTransient();
			_userExists = false;
			throw new SeedpodException( "No result set. " );
		} else {
			super.load( rs );

			_userName = super.getAttributeValue( SeedpodModel.RdbSlot.USERNAME ).getStringValue();
			_firstName = super.getAttributeValue( SeedpodModel.RdbSlot.FIRST_NAME ).getStringValue();
			_lastName = super.getAttributeValue( SeedpodModel.RdbSlot.LAST_NAME ).getStringValue();
			_password = super.getAttributeValue( SeedpodModel.RdbSlot.PASSWORD ).getStringValue();
		}

	}

	public void login( boolean l ) {
		_isLoggedIn = l;
	}

	public void logout() {
		_isLoggedIn = false;
	}

}
